﻿using Net.Event;
using Net.Helper;
using Net.Share;
using System.Diagnostics;

namespace ServerStressTesting
{
    public partial class Form1 : Form
    {
        private Server server;
        private bool run;

        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            NDebug.BindDebug(new FormDebug(listBox1, null) { count = 100000 });
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1_Click(null, null);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (run)
            {
                server?.Close();
                run = false;
                return;
            }
            int port = int.Parse(textBox2.Text);//设置端口
            server = new Server();//创建服务器对象
            server.Config.SendBufferSize = 1024;
            server.Config.ReceiveBufferSize = 1024;
            server.Config.OnlineLimit = 50000;//服务器最大运行2500人连接
            server.Config.LineUp = 50000;
            server.Config.RTO = 1000;
            server.Config.MTU = 1300;
            server.Config.MTPS = 2048;
            server.Config.FlowControl = FlowControlMode.Quick;
            server.SetKeepAliveTimeout(1000 * 60 * 20);
            server.OnNetworkDataTraffic += (df) => //当统计网络性能,数据传输量
            {
                toolStripStatusLabel1.Text = $"流出:{df.SentPacketsPerSecond}次/{ByteHelper.ToString(df.SentBytesPerSecond)} " +
                $"流入:{df.ReceivedPacketsPerSecond}次/{ByteHelper.ToString(df.ReceivedBytesPerSecond)} " +
                $"解析:{df.RpcResolveCount}次 " +
                $"总流入:{ByteHelper.ToString(df.TotalReceivedBytes)} 总流出:{ByteHelper.ToString(df.TotalSentBytes)} {df.FormatFrameRates()}";
                label2.Text = "登录:" + server.OnlinePlayers + " 未登录:" + server.OnlineUnPlayers;
            };
            server.AddAdapter(new Net.Adapter.SerializeAdapter3());
            server.AddAdapter(new Net.Adapter.CallSiteRpcAdapter());
            server.Run((ushort)port);//启动
            run = true;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            server?.Close();
            Process.GetCurrentProcess().Kill();
        }

        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == -1)
                return;
            var item = listBox1.SelectedItem;
            if (item == null)
                return;
            MessageBox.Show(item.ToString());
        }
    }
}
